import React, {Component} from 'react';
import PropTypes from 'prop-types';

const { Provider, Consumer } = React.createContext();

class Parent extends Component {
  static childContextTypes = {
    value: PropTypes.number,
    name: PropTypes.string,
  }
  constructor(props) {
    super(props);
    this.state = {
      value: 321321,
      name: 'context'
    }
  }
  getChildContext() {
    return {
      value: this.state.value,
      name: this.state.name,
    }
  }
  render() {
    return (
      <Provider value={this.state}>
        {this.props.children}
      </Provider>
    )
  }
}

class Child extends Component {
  static contextTypes = {
    value: PropTypes.number,
    name: PropTypes.string,
  }
  render() {
    return (
      <div>
        <p>
          {this.context.name}: {this.context.value}
        </p>
      </div>
    )
  }
}

const Child2 = () => (
  // 传入一个function
  <Consumer>
    {value => (
      <p>nexContext: {value.value}</p>
    )}
  </Consumer>
)

export default class ContextDemo extends Component {

  render() {
    return (
      <Parent>
        <Child />
        <Child2 />
      </Parent>
    )
  }
}
